package cn.darven.ui;

import javax.swing.*;
import javax.swing.text.html.HTMLEditorKit;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;

/**
 * @author darven
 * @date 2025/11/3
 * @description 转换管理类
 */
public class TransformManager {
    private MainFrame mainFrame;

    public TransformManager(MainFrame mainFrame) {
        this.mainFrame = mainFrame;
    }

    public void performTransform() {
        DatabaseManager databaseManager = mainFrame.getDatabaseManager();
        if (databaseManager.getSqlServerDB() == null) {
            JOptionPane.showMessageDialog(mainFrame, "请先连接数据库");
            return;
        }
        mainFrame.updateStatus("正在执行查询");
        String xmlContent = databaseManager.getSqlServerDB().fetchXmlData();
        mainFrame.updateStatus("查询完成");

        mainFrame.updateStatus("开始转换");
        File file = new File("src/main/resources/output/output.html");
        databaseManager.getXsltTransformer().transformToHtmlFile(xmlContent, "src/main/resources/xslt/contact.xsl", file.getAbsolutePath());
        mainFrame.updateStatus("转换完成");

        try {
            JFrame jFrame=new JFrame("XML转化HTML");
            JEditorPane textArea = new JEditorPane();
            textArea.setContentType("text/html");
            textArea.setPage(file.toURI().toURL());
            jFrame.add(textArea);
            jFrame.setSize(800, 600);
            jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            jFrame.setLocationRelativeTo(null);
            jFrame.setVisible(true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}